package org.chen.wordwave.act;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.credentials.CredentialManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson2.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.ResultBody;
import org.chen.wordwave.bean.UserGoogleLoginRequest;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.bean.UserLoginRequest;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.email.EmailCheckUtils;
import org.litepal.LitePal;

import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Login extends BaseActivity {
    private static final int RC_SIGN_IN = 9001;
    private GoogleSignInClient mGoogleSignInClient;
    private SignInButton googleSignInButton;

    private EditText et_pwd,et_email;
    private TextView tv_forget_pwd,tv_title,tv_register,tv_toggle_jzmm,question_login;
    private ImageView iv_goback;
    private Button btn_login;
    private CheckBox cb_remember_me;
    private ToastParams params = new ToastParams();
    private ApiService apiService;
    private ProgressDialog progressDialog;

    private EditText etPwd;
    private ImageView ivPasswordToggle;
    private boolean isPasswordVisible = false;

    private void configureGoogleSignIn() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestId()
                .requestProfile()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // 检查是否已经登录
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            // 用户已经登录，可以选择自动登录或显示登录状态
            Log.d("GoogleSignIn", "User already signed in: " + account.getEmail());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        configureGoogleSignIn();

        // 初始化Google登录按钮
        googleSignInButton = findViewById(R.id.google_sign_in_button);
        googleSignInButton.setSize(SignInButton.SIZE_STANDARD);
        googleSignInButton.setOnClickListener(v -> signIn());

        apiService = ApiClient.getClient(this).create(ApiService.class);

        etPwd = findViewById(R.id.et_pwd);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);

        TextView tvVisitorAccess = findViewById(R.id.tv_visitor_access);
        tvVisitorAccess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 进入主界面
                showPrivacyPolicyDialog();
            }
        });

        setupPasswordToggle();
    }

    private void setupPasswordToggle() {
        ivPasswordToggle.setOnClickListener(v -> {
            if (isPasswordVisible) {
                // 隐藏密码
                etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_visibility_off);
                isPasswordVisible = false;
            } else {
                // 显示密码
                etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_visibility);
                isPasswordVisible = true;
            }
            // 将光标移到文本末尾
            etPwd.setSelection(etPwd.getText().length());
        });
    }

    private void signIn() {
        mGoogleSignInClient.signOut().addOnCompleteListener(this, task -> {
            showProgressDialog();
            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, RC_SIGN_IN);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            if (account == null) {
                handleLoginError(getString(R.string.google_sign_in_failed));
                dismissProgressDialog();
                return;
            }

            // 获取用户信息
            String email = account.getEmail();
            String displayName = account.getDisplayName();
            String googleId = account.getId();
            String idToken = account.getIdToken(); // 如果需要验证token

            Log.d("GoogleSignIn", "Email: " + email + ", Name: " + displayName + ", ID: " + googleId);

            if (email == null || googleId == null) {
                handleLoginError("获取用户信息失败");
                dismissProgressDialog();
                return;
            }

            // 调用后端API
            UserGoogleLoginRequest request = new UserGoogleLoginRequest(email, googleId, displayName);
            Call<ResultBody> call = apiService.googleLogin(request);

            call.enqueue(new Callback<ResultBody>() {
                @Override
                public void onResponse(@NonNull Call<ResultBody> call, @NonNull Response<ResultBody> response) {
                    dismissProgressDialog();

                    if (!response.isSuccessful()) {
                        handleLoginError("服务器响应错误: " + response.code());
                        return;
                    }

                    ResultBody body = response.body();
                    if (body == null) {
                        handleLoginError("服务器返回数据为空");
                        return;
                    }

                    if ("200".equals(body.getCode())) {
                        try {
                            Object result = body.getResult();
                            UserInfo userInfo = JSONObject.from(result).toJavaObject(UserInfo.class);
                            handleLoginSuccess(userInfo);
                        } catch (Exception e) {
                            Log.e("GoogleSignIn", "解析用户信息失败", e);
                            handleLoginError("用户信息解析失败");
                        }
                    } else {
                        handleLoginError(body.getMessage() != null ? body.getMessage() : "登录失败");
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ResultBody> call, @NonNull Throwable t) {
                    dismissProgressDialog();
                    Log.e("GoogleSignIn", "网络请求失败", t);
                    handleLoginError(getString(R.string.network_error));
                }
            });

        } catch (ApiException e) {
            dismissProgressDialog();
            Log.e("GoogleSignIn", "Google sign in failed, status code: " + e.getStatusCode(), e);

            String errorMessage;
            switch (e.getStatusCode()) {
                case 7: // NETWORK_ERROR
                    errorMessage = "网络连接失败，请检查网络";
                    break;
                case 8: // INTERNAL_ERROR
                    errorMessage = "内部错误，请稍后重试";
                    break;
                case 10: // DEVELOPER_ERROR
                    errorMessage = "配置错误，请联系开发者";
                    break;
                case 12500: // SIGN_IN_CANCELLED
                    errorMessage = "登录已取消";
                    break;
                case 12501: // SIGN_IN_CURRENTLY_IN_PROGRESS
                    errorMessage = "登录正在进行中";
                    break;
                case 12502: // SIGN_IN_FAILED
                    errorMessage = "登录失败，请重试";
                    break;
                default:
                    errorMessage = "Google登录失败: " + e.getStatusCode();
            }
            handleLoginError(errorMessage);
        }
    }

    private void handleLoginSuccess(UserInfo userInfo) {
        // 保存用户信息
        WordInit.userInfo = userInfo;
        if (cb_remember_me.isChecked()) {
            WordInit.flyerEditor.putString("email", userInfo.getEmail());
            WordInit.flyerEditor.putString("account", userInfo.getAccount());
            WordInit.flyerEditor.putString("registerTime", userInfo.getRegisterTime());
            WordInit.flyerEditor.commit();
        }

        // 保存到数据库
        UserInfo first = LitePal.findFirst(UserInfo.class);
        if (first == null) {
            userInfo.save();
        } else {
            LitePal.deleteAll(UserInfo.class);
            userInfo.save();
        }

        ToastParams toastParams = new ToastParams();
        toastParams.style = new CustomToastStyle(R.layout.success);
        toastParams.text = getString(R.string.login_success);
        Toaster.show(toastParams);

        startActivity(new Intent(Login.this, Main.class));
    }

    private void handleLoginError(String errorMessage) {
        params.text = errorMessage;
        params.style = new CustomToastStyle(R.layout.error);
        Toaster.show(params);
    }

    @Override
    public Integer getLayoutResId() {
        return  R.layout.login_act;
    }

    @Override
    public void init() {

        tv_forget_pwd = findViewById(R.id.tv_forget_pwd);
        et_pwd = findViewById(R.id.et_pwd);
        et_email = findViewById(R.id.et_email);
        iv_goback = findViewById(R.id.iv_goback);
        tv_title = findViewById(R.id.tv_title);
        tv_register = findViewById(R.id.tv_register);
        btn_login = findViewById(R.id.btn_login);
        cb_remember_me = findViewById(R.id.cb_remember_me);
        question_login = findViewById(R.id.question_login);
        tv_title.setText(R.string.login);
        tv_toggle_jzmm = findViewById(R.id.tv_toggle_jzmm);
        tv_toggle_jzmm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cb_remember_me.setChecked(!cb_remember_me.isChecked());
            }
        });

//        注册
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Register.class));
            }
        });
//        设置返回按钮不显示
        iv_goback.setVisibility(View.GONE);
//        登录监听
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
                String email=et_email.getText().toString().trim();
                String pwd=et_pwd.getText().toString().trim();

                if (email.isEmpty()){
                    et_email.setError(getString(R.string.phone_not_nu));
                    dismissProgressDialog();
                    return;
                }

                if (EmailCheckUtils.isEmailLegal(email)){
                    et_email.setError(getString(R.string.phone_no_valid));
                    dismissProgressDialog();
                    return;
                }
//                取消错误提示
                et_email.setError(null);

                if (pwd.isEmpty()){
                    et_pwd.setError(getString(R.string.password_empty));
                    dismissProgressDialog();
                    return;
                }
                et_pwd.setError(null);
                UserLoginRequest request = new UserLoginRequest(email, pwd);
                apiService.login(request).enqueue(new Callback<ResultBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResultBody> call, @NonNull Response<ResultBody> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ResultBody body = response.body();
                            if (body.getMessage().equals("400") && body.getCode().equals("-1")){
                                params.text = getString(R.string.login_fail);
                                params.style = new CustomToastStyle(R.layout.error);
                                Toaster.show(params);
                                dismissProgressDialog();
                            }else if (body.getCode().equals("400")){
                                params.text = getString(R.string.login_fail_account);
                                params.style = new CustomToastStyle(R.layout.error);
                                Toaster.show(params);
                                dismissProgressDialog();
                            }else {
                                Object result = response.body().getResult();
                                UserInfo userInfo = JSONObject.from(result).toJavaObject(UserInfo.class);
                                if (userInfo.getBan().equals("true")){
                                    Toaster.show(getString(R.string.ban));
                                    dismissProgressDialog();
                                }else {
                                    // 检查会员状态
                                    if (userInfo.isMember() && userInfo.getMembershipExpiryDate() != null) {
                                        Date currentDate = new Date();
                                        if (currentDate.after(userInfo.getMembershipExpiryDate())) {
                                            userInfo.setMember(false);
                                            userInfo.setMembershipExpiryDate(null);
                                            if (userInfo.getMembershipType() == 2) {
                                                userInfo.setMembershipType(0);
                                            }
                                        }
                                    }

                                    if (cb_remember_me.isChecked()) {
                                        WordInit.flyerEditor.putString("email", userInfo.getEmail());
                                        WordInit.flyerEditor.putString("account", userInfo.getAccount());
                                        WordInit.flyerEditor.putString("registerTime", userInfo.getRegisterTime());
                                        WordInit.flyerEditor.commit();
                                    }
                                    WordInit.userInfo = userInfo;
                                    UserInfo first = LitePal.findFirst(UserInfo.class);
                                    if (first == null) {
                                        userInfo.save();
                                    } else {
                                        LitePal.deleteAll(UserInfo.class);
                                        userInfo.save();
                                    }
                                    ToastParams toastParams = new ToastParams();
                                    toastParams.style = new CustomToastStyle(R.layout.success);
                                    toastParams.text = getString(R.string.login_success);
                                    Toaster.show(toastParams);
                                    startActivity(new Intent(Login.this, Main.class));
                                    dismissProgressDialog();
                                }
                            }
                        } else {
                            params.text = getString(R.string.login_fail);
                            params.style = new CustomToastStyle(R.layout.error);
                            Toaster.show(params);
                            dismissProgressDialog();
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResultBody> call,@NonNull Throwable t) {
                        params.text = getString(R.string.network_error);
                        params.style = new CustomToastStyle(R.layout.error);
                        Toaster.show(params);
                        dismissProgressDialog();
                    }
                });
            }
        });

        tv_forget_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, ForgotPasswordOnline.class));
            }
        });
        question_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                emailIntent.setData(Uri.parse("mailto:xchen6367@gmail.com")); // 设置开发者的电子邮件地址
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.wordmaster_email)); // 设置电子邮件主题
                if (emailIntent.resolveActivity(getPackageManager()) != null) {
                    startActivity(emailIntent);
                }
            }
        });
    }

    private void showPrivacyPolicyDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_privacy_policy_login, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();

        Button btnAgree = dialogView.findViewById(R.id.btn_agree);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        TextView tvPrivacyPolicy = dialogView.findViewById(R.id.tv_privacy_policy);

        tvPrivacyPolicy.setMovementMethod(new ScrollingMovementMethod());

        btnAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startActivity(new Intent(Login.this, Main.class));
                finish();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        删除之前的页面，主要用户主界面点击退出登录之后返回该界面，并移除其他界面
        ActivityUtils.finishAllActivitiesExceptNewest();
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(getString(R.string.uploading));
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
